// 信号量类，用于控制并发数
import 'dart:async';

class Semaphore {
  final int _maxCount;
  int _currentCount;
  final List<Completer<void>> _waiters = [];

  Semaphore(this._maxCount) : _currentCount = _maxCount;

  Future<void> acquire() async {
    if (_currentCount > 0) {
      _currentCount--;
      return;
    }

    final completer = Completer<void>();
    _waiters.add(completer);
    return completer.future;
  }

  void release() {
    if (_waiters.isNotEmpty) {
      final completer = _waiters.removeAt(0);
      completer.complete();
    } else {
      _currentCount++;
    }
  }
}
